package com.lisa.auto.service.excel.impl;

import javax.servlet.http.HttpServletResponse;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lisa.auto.entity.ComdPo;
import com.lisa.auto.entity.ceramics.ResultPo;
import com.lisa.auto.entity.ceramics.bo.BaseSingleBo;
import com.lisa.auto.entity.ceramics.po.CeramicsGoodsPo;
import com.lisa.auto.entity.excel.GoodsTmplPo;
import com.lisa.auto.entity.excel.OrderTmplPo;
import com.lisa.auto.entity.seveneleven.po.SevenElevenShopAddrPo;
import com.lisa.auto.entity.seveneleven.po.SevenElevenVehiclePo;
import com.lisa.auto.service.ComdService;
import com.lisa.auto.tools.ceramics.CeramicsComs;
import com.lisa.auto.tools.seveneleven.DataBaseConnect;
import com.lisa.auto.tools.seveneleven.SevenElevenComs;
import com.lisa.auto.util.DateUtil;
import com.lisa.auto.util.ExcelUtils;
import com.lisa.auto.util.JxlExcelUtils;
import com.lisa.redis.JedisClusterUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.lisa.auto.service.excel.CeramicsImportService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 陶瓷转换工具
 * @author huangzhigang 20200113
 */
@Service
public class CeramicsImportServiceImpl implements CeramicsImportService {

	static final Logger logger = LoggerFactory.getLogger(CeramicsImportServiceImpl.class);

	static String SHEET_TITLE_ = "SheetJS";

	static String ENTITY_ = "entity";

	static String DATA_ = "data";

	@Autowired
	private ComdService comdService;

	/**
	 * 陶瓷转换工具
	 * @param fileList 订单/原始单
	 * @param response
	 */
	@Override
	public List<ResultPo> importExcel(List<MultipartFile> fileList, HttpServletResponse response) {
		List<ResultPo> errList = new ArrayList<>();
		try {
			List<OrderTmplPo> result = new ArrayList<>();
			if (CollectionUtils.isEmpty(fileList)){
				errList.add(new ResultPo(1, "", "上传数据为空"));
				errList.add(new ResultPo(1, "", "上传数据为空", "", ""));
				return errList;
			}
			List<ComdPo> comdList = comdService.selComdList();
			for (MultipartFile file : fileList){
				HashMap<String, String> errMap = new HashMap<>();
				if (file == null){
					errList.add(new ResultPo(1, file.getOriginalFilename(), "上传数据为空", "", ""));
					return errList;
				}
				LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
				fieldMap.put("商品编号", "goodNum");
				fieldMap.put("商品全名", "goodName");
				fieldMap.put("单位", "company");
				fieldMap.put("数量", "quantity");
				String[] uniqueFields = new String[]{"商品编号", "商品全名", "单位", "数量"};
				List<CeramicsGoodsPo> ceramicsGoodsList = JxlExcelUtils.excelToList(file.getInputStream(), "导出数据", CeramicsGoodsPo.class, fieldMap, uniqueFields);
				String compNum = JxlExcelUtils.excelToListRows(file.getInputStream(), "导出数据", "单位编号");
				String compAddr = JxlExcelUtils.excelToListRows(file.getInputStream(), "导出数据", "购买单位");
				/** 查询城配系统中所有地址 */
				List<SevenElevenShopAddrPo> addrList = DataBaseConnect.execute(11);
				if (CollectionUtils.isEmpty(addrList)){
					logger.info("查询城配系统中所有地址为空 Json = {}", JSONArray.toJSONString(addrList));
				}
				if (CollectionUtils.isEmpty(ceramicsGoodsList)){
					errList.add(new ResultPo(1, "", "转换数据为空"));
					return errList;
				}
				List<GoodsTmplPo> goodsTmplList = new ArrayList<>();
				OrderTmplPo orderTmpl = CeramicsComs.initData();
				orderTmpl.setMerchantCode(CeramicsComs.MERCHANT_NUM);
				orderTmpl = addrNum(compNum, addrList, orderTmpl);
				for (CeramicsGoodsPo ceramics : ceramicsGoodsList){
					if (ceramics == null){
						continue;
					}
					/** 商品数量 */
					String goodQuantity = ceramics.getQuantity();
					if (StringUtils.isBlank(goodQuantity)){
						continue;
					}
					if ("数量".equals(goodQuantity)){
						continue;
					}
					/** 运单包裹信息处理 */
					CeramicsComs.goodsDB(comdList, ceramics, Integer.parseInt(goodQuantity), goodsTmplList);
				}
				orderTmpl.setGoodsTmplList(goodsTmplList);
				if (StringUtils.isBlank(orderTmpl.getUnloadingAddrNo()) && StringUtils.isBlank(orderTmpl.getUnloadingAddr())){
					errList.add(new ResultPo(1, file.getOriginalFilename(), "地址不在系统中，请先录入地址", compNum, compAddr));
				}else {
					result.add(orderTmpl);
				}
			}
			if (CollectionUtils.isNotEmpty(result)){
				JedisClusterUtil.set(JxlExcelUtils.DATA_KEY, JSONObject.toJSONString(result));
			}
			return errList;
		}catch (Exception e){
			System.out.println(e.getMessage());
			logger.info(e.getMessage(), e);
		}
		return errList;
	}

	public static OrderTmplPo addrNum(String compNum, List<SevenElevenShopAddrPo> addrList, OrderTmplPo orderTmpl){
		if (CollectionUtils.isEmpty(addrList)){
			return null;
		}
		List<SevenElevenShopAddrPo> shopAddrPos = addrList.stream().filter(t -> t.getShopId().equals(compNum)).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(shopAddrPos)){
			orderTmpl.setUnloadingAddrNo(shopAddrPos.get(0).getShopAddrNo());
			orderTmpl.setUnloadingAddr(shopAddrPos.get(0).getShopAddr());
			orderTmpl.setConsignee("默认");
			orderTmpl.setConsigneeTelNum("0755-28537427");
			return orderTmpl;
		}
		return orderTmpl;
	}

	/**
	 * 解析城配车次Excel
	 * @param baseFile 订单/原始单
	 * @param loadFile 车次列表
	 * @param response
	 */
	@Override
	public void importLoadExcel(MultipartFile baseFile, MultipartFile loadFile, HttpServletResponse response) {
		try {
			/** 解析陶瓷原始单/订单 */
			String excelHeader = "{\"单位编号\":\"compNum\",\"客户地址\":\"cusAddr\"}";
			String excelBody = "{\"条码\":\"barCode\",\"商品名称\":\"goodName\",\"数量\":\"goodQuantity\",\"备注\":\"remarks\"}";
			List<BaseSingleBo> singleList = ExcelUtils.readCeramicsExcel(baseFile.getInputStream(), excelHeader, excelBody, Boolean.TRUE);
			logger.info("原始单为空 Json = {}", JSONArray.toJSONString(singleList));

			/** 解析车次列表 */
			List<String> columnName2 = Arrays.asList(new String[]{"企业","车次编号","司机","车牌号","司机手机","剩余体积m³","剩余重量kg","司机收入费用","车次状态","取货地址","取货地址编号","取货时间段","客户/品牌名","外部运单编号","卸货地址","外部店铺编号","卸货地址编号","卸货联系人","卸货联系人电话","卸货时间段","包裹类型","包裹名称","包裹编号","包裹容积","包裹重量","运费","备注"});
			String vehicleJson = ExcelUtils.readExcel(loadFile, SHEET_TITLE_, columnName2);
			String resultVehicle = SevenElevenComs.vehicleDb(vehicleJson);
			List<SevenElevenVehiclePo> vehicleList = JSONArray.parseArray(resultVehicle, SevenElevenVehiclePo.class);
			List<String> ids = new ArrayList<>();
			List<SevenElevenVehiclePo> vehicleFilter = vehicleList.stream().filter(
					v -> {
						boolean flag = !ids.contains(v.getShopId());
						ids.add(v.getShopId());
						return flag;
					}
			).collect(Collectors.toList());
			Map<String, List<BaseSingleBo>> baseSingleGroup = singleList.stream().collect(Collectors.groupingBy(BaseSingleBo::getCompNum));
			Map<String, List<SevenElevenVehiclePo>> vehicleGroup = vehicleFilter.stream().collect(Collectors.groupingBy(SevenElevenVehiclePo::getPlate));
			String[] titleRow = {"条码","商品名称","数量","备注"};
			ExcelUtils.excelExport(vehicleGroup, baseSingleGroup, titleRow, response);
		}catch (Exception e){
			logger.info(e.getMessage(), e);
		}
	}
}
